package com.glorious.gcontacts.spring.services;

import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import org.springframework.stereotype.Service;

import com.glorious.gcontacts.model.UserData;
import com.google.appengine.api.users.User;

@SuppressWarnings("unchecked")
@Service
public class CacheService
{
	private static final Logger logger = Logger.getLogger(CacheService.class.getName());
	
	private Cache cache;
	
	private static CacheService instance = null;
	
	public CacheService()
	{
		logger.log(Level.INFO, "Creating the memcache...");
		instance = this;
		try
		{
			CacheFactory factory = CacheManager.getInstance().getCacheFactory();
			cache = factory.createCache(Collections.emptyMap());
			logger.log(Level.INFO, "Memcache created");
		}
		catch (CacheException e)
		{
			logger.log(Level.SEVERE, "Error creating the cache", e);
		}
	}
	
	public static CacheService getInstance()
	{
		return instance;
	}
	
	private String getUserKey(User user)
	{
		return String.format("userdata_%s", user.getUserId());
	}
	
	public boolean isUserDataCached(User user)
	{
		return cache.containsKey(getUserKey(user));
	}
	
	public UserData getUserData(User user)
	{
		return (UserData)cache.get(getUserKey(user));
	}
	
	public void setUserData(UserData user)
	{
		cache.put(getUserKey(user.getUser()), user);
	}
	
}
